package org.zht.dormpro.auth.service.impl;

import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zht.dormpro.pub.exception.DataBaseException;
import org.zht.dormpro.auth.mapper.SysPermissionMapper;
import org.zht.dormpro.auth.model.SysPermission;
import org.zht.dormpro.auth.service.ISysPermissionService;

import java.util.List;

@Service
public class SyspermissionServiceImpl implements ISysPermissionService {
    private static final Logger logger = Logger.getLogger(SyspermissionServiceImpl.class);
    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public List<SysPermission> listMenu(String menuName) {
        //查询当前菜单的路径
        String parentIds = null;
        SysPermission p = null;
        if (StrUtil.isNotBlank(menuName) && !StrUtil.equals("0",menuName)) {
            p = sysPermissionMapper.selectByPrimaryKey(Integer.valueOf(menuName));
            if (p != null) {
                parentIds = p.getParentIds();
                parentIds = parentIds+"/"+menuName;
            }
        }
        List<SysPermission> allMenuTree = sysPermissionMapper.getAllMenuTree(parentIds);
        if(p!=null){
            allMenuTree.add(p);
        }
        return allMenuTree;
    }

    @Override
    public int addMenu(SysPermission menu) throws DataBaseException {
        int id = 0;
        try {
            id = sysPermissionMapper.insertSelective(menu);
        } catch (Exception e) {
            logger.error(e, e);
            throw new DataBaseException("数据库错误");
        }
        return id;
    }

    @Override
    public SysPermission getSysPermission(Integer parentId) {
        return sysPermissionMapper.selectByPrimaryKey(parentId);
    }

    @Override
    public boolean deleteMenu(Integer menuId) {
        int i = sysPermissionMapper.deleteByPrimaryKey(menuId);
        //删除其子菜单
        if (i > 0) {
            sysPermissionMapper.deleteSonMenu(menuId);
        }
        return i > 0;
    }

    @Override
    public boolean editMenu(SysPermission newMenu) {
        //查询原有的父menu
        SysPermission sysPermission = sysPermissionMapper.selectByPrimaryKey(newMenu.getParentId());
        if(sysPermission!=null){
            String parentIds = sysPermission.getParentIds();
            newMenu.setParentIds(parentIds+"/"+newMenu.getParentId());
        }
        int i = sysPermissionMapper.updateByPrimaryKeySelective(newMenu);
        return i > 0;
    }

    @Override
    public List<SysPermission> getHasChildMenu() {
        return sysPermissionMapper.getHasChildMenu();
    }
}
